@echo off
chcp 65001 > nul
echo ===================================================================
echo   快速重新部署到远程服务器
echo ===================================================================
echo.
echo 此脚本将：
echo 1. 重新构建 Docker 镜像（包含最新的 CORS 修复）
echo 2. 上传到远程服务器
echo 3. 重启容器
echo.

REM 配置变量（与 upload2remote.bat 保持一致）
set IMAGE_NAME=appexecel2student
set TAR_DIR=d:\temp\tar
set CONTAINER_NAME=appexecel2student
set REMOTE_USER=gpzx
set REMOTE_HOST=192.168.50.218
set REMOTE_TAR_DIR=/bak/tar
set BACKEND_PORT=7661
set FRONTEND_PORT=7662
set NETWORK_NAME=mynet

set TAR_FILE=%TAR_DIR%\%IMAGE_NAME%.tar

echo [1/5] 构建新的 Docker 镜像...
docker build -t %IMAGE_NAME% .
if %errorlevel% neq 0 (
    echo [错误] 构建失败！
    pause
    exit /b 1
)
echo.

echo [2/5] 保存镜像为 tar 文件...
docker save -o "%TAR_FILE%" %IMAGE_NAME%
if %errorlevel% neq 0 (
    echo [错误] 保存失败！
    pause
    exit /b 1
)
echo.

echo [3/5] 上传到远程服务器...
scp -F nul "%TAR_FILE%" %REMOTE_USER%@%REMOTE_HOST%:%REMOTE_TAR_DIR%/
if %errorlevel% neq 0 (
    echo [错误] 上传失败！
    pause
    exit /b 1
)
echo.

echo [4/5] 在远程服务器上重新加载并启动...
ssh -F nul %REMOTE_USER%@%REMOTE_HOST% "docker stop %CONTAINER_NAME% 2>&1 || true && docker rm %CONTAINER_NAME% 2>&1 || true && docker load -i %REMOTE_TAR_DIR%/%IMAGE_NAME%.tar && docker run -d --name %CONTAINER_NAME% -p %BACKEND_PORT%:3000 -p %FRONTEND_PORT%:80 --network=%NETWORK_NAME% --restart unless-stopped %IMAGE_NAME%"
if %errorlevel% neq 0 (
    echo [错误] 远程部署失败！
    pause
    exit /b 1
)
echo.

echo [5/5] 检查容器状态...
ssh -F nul %REMOTE_USER%@%REMOTE_HOST% "docker ps | grep %CONTAINER_NAME%"
echo.

echo ===================================================================
echo                    重新部署完成！
echo ===================================================================
echo.
echo 访问地址:
echo   前端: http://%REMOTE_HOST%:%FRONTEND_PORT%
echo   后端: http://%REMOTE_HOST%:%BACKEND_PORT%
echo.
echo 查看日志:
echo   ssh -F nul %REMOTE_USER%@%REMOTE_HOST% "docker logs %CONTAINER_NAME%"
echo.
pause
